package com.wisdom.client.proxy;

import com.alibaba.fastjson.JSON;
import com.wisdom.client.rpc.RpcRequestManager;
import com.wisdom.core.data.RpcRequest;
import com.wisdom.core.data.RpcResponse;
import com.wisdom.core.factory.SpringBeanFactory;
import com.wisdom.core.util.RequestIdUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;

/**
 * @description
 * @author: ts
 * @create:2021-05-12 00:11
 */
@Slf4j
public class CglibProxyCallBackHandler implements MethodInterceptor {


    public Object intercept(Object o, Method method, Object[] parameters, MethodProxy methodProxy) throws Throwable {
        //跳过void类型的逻辑处理
        if (ReflectionUtils.isObjectMethod(method)) {
            return method.invoke(method.getDeclaringClass().newInstance(), parameters);
        }
        //封装rpcRequest
        RpcRequest rpcRequest = RpcRequest
                .builder()
                .requestId(RequestIdUtil.requestId())
                .className(method.getDeclaringClass().getName())
                .methodName(method.getName())
                .parameters(parameters)
                .parameterTypes(method.getParameterTypes())
                .build();
        log.info("build rpcRequest success, rpcRequest is {}", JSON.toJSONString(rpcRequest));
        RpcRequestManager requestManager = SpringBeanFactory.getBean(RpcRequestManager.class);
        RpcResponse rpcResponse = requestManager.sendRequest(rpcRequest);
        return rpcResponse.getResult();
    }

}
